const { Successmodel, Errormodel } = require("../model/responseModel");
const { getlist, getdetail, createNewBlog ,updateBlogData,deleteBlogData} = require("../controllers/blog");

const handleBlogRoute = (req, res) => {
  const method = req.method;
  const id = req.query.id;
  const blogData = req.body
  if (method == "GET" && req.path === "/api/blog/list") {
    const author = req.query.author || "";
    const keyword = req.query.keyword || "";
    const listdataPromise = getlist(author, keyword);
    return listdataPromise.then((listdata) => {
      return new Successmodel(listdata);
    },(error)=>{
        return new Errormodel(error)
    });
  }
  if (method == "GET" && req.path === "/api/blog/detail") {
    const id = req.query.id || "";
    const detaildataPromise = getdetail(id);
    return detaildataPromise.then((detaildata) => {
      return new Successmodel(detaildata);
    },(error)=>{
        return new Errormodel(error)
    });
  }
  if (method == "POST" && req.path === "/api/blog/new") {
    const author = 'zhaoliu'
    req.body.author = author
    const NewBlogPromise = createNewBlog(blogData);
    return NewBlogPromise.then(newBlogData => {
        return new Successmodel(newBlogData);
    },(error)=>{
        return new Errormodel(error)
    });
  }
  if (method == "POST" && req.path === "/api/blog/update") {
    const updatedBlogPromise = updateBlogData(id,blogData);
    return updatedBlogPromise.then(updatedBlogData=> {
        if(updatedBlogData)  
            return new Successmodel('更新博客成功');
        else  
            return new Errormodel('更新博客失败');
    });
  } 
  if (method == "POST" && req.path === "/api/blog/delete") {
    const author = 'lisi'
    const deletedBlogPromise = deleteBlogData(id,author);
    return deletedBlogPromise.then(deleteBlogData=> {
        if(deleteBlogData)  
            return new Successmodel('删除博客成功');
        else  
            return new Errormodel('删除博客失败');
    });
  }
};

module.exports = handleBlogRoute;
